import { useState } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Alert, AlertDescription } from './ui/alert';
import { Loader2, Database, Lock, User } from 'lucide-react';
import { useAuth } from '../lib/auth/context';
import { useI18n } from '../lib/i18n/context';
import { useDataSource } from '../lib/data/context';

export function LoginForm() {
  const { t } = useI18n();
  const { login, isLoading } = useAuth();
  const { dataSource, fetchDatabases, fetchSlowQueries } = useDataSource();
  const [credentials, setCredentials] = useState({
    username: '',
    password: ''
  });
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!credentials.username || !credentials.password) {
      setError(t.auth.validation.required);
      return;
    }

    try {
      await login(credentials);
      // After successful login, fetch data if using backend
      if (dataSource === 'backend') {
        await fetchDatabases();
        await fetchSlowQueries();
      }
    } catch (err) {
      setError(t.auth.errors.invalidCredentials);
    }
  };

  const handleInputChange = (field: keyof typeof credentials) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setCredentials(prev => ({
      ...prev,
      [field]: e.target.value
    }));
    // Clear error when user starts typing
    if (error) setError(null);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center space-y-2">
          <div className="flex justify-center">
            <div className="flex items-center justify-center w-16 h-16 bg-primary/10 rounded-full">
              <Database className="h-8 w-8 text-primary" />
            </div>
          </div>
          <CardTitle className="text-2xl">{t.auth.login.title}</CardTitle>
          <CardDescription>
            {t.auth.login.description}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <Alert variant="destructive">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}
            
            <div className="space-y-2">
              <Label htmlFor="username">{t.auth.form.username}</Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="username"
                  type="text"
                  placeholder={t.auth.form.usernamePlaceholder}
                  value={credentials.username}
                  onChange={handleInputChange('username')}
                  className="pl-10"
                  disabled={isLoading}
                  autoComplete="username"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">{t.auth.form.password}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="password"
                  type="password"
                  placeholder={t.auth.form.passwordPlaceholder}
                  value={credentials.password}
                  onChange={handleInputChange('password')}
                  className="pl-10"
                  disabled={isLoading}
                  autoComplete="current-password"
                />
              </div>
            </div>

            <Button 
              type="submit" 
              className="w-full" 
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {t.auth.login.loggingIn}
                </>
              ) : (
                t.auth.login.signIn
              )}
            </Button>
          </form>

          <div className="mt-6 text-center">
            <div className="text-sm text-muted-foreground">
              {t.auth.login.demoCredentials}
            </div>
            <div className="text-xs text-muted-foreground mt-1">
              {t.auth.login.demoUsername}: admin | {t.auth.login.demoPassword}: password
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}